package com.eranga.project.services;

import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import com.eranga.project.control.data.LogDS;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	private static final String TAG = "MyService";
	int TIMEOUT_MILLISEC = 600;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {

		Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onCreate");
		
		new SyncData().execute();
		
	}

	@Override
	public void onStart(Intent intent, int startId) {
		
		Toast.makeText(this, "Congrats! MyService onStart", Toast.LENGTH_LONG).show();
		
		new SyncData().execute();
	}


	
	@Override
	public void onDestroy() {
		Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
		Log.d(TAG, "onDestroy");
	}
	
	
	
	/**
	 * 
	 * @author ifras
	 * 
	 */
	class SyncData extends AsyncTask<String, String, String> {

		protected String doInBackground(String... args) {
			try {
				
				LogDS ds=new LogDS(getApplicationContext());
				
				String SETTINGS = "SETTINGS";
				SharedPreferences localSP = getSharedPreferences(SETTINGS, Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);

				//if(localSP.getString("Status", "").equals("Success")){
				
				ArrayList<com.eranga.project.model.Log> list=ds.getAllUnSync();
		
			if(!list.isEmpty())
				for (com.eranga.project.model.Log log : list) {
					
					JSONObject json = new JSONObject();
					
					json.put("log_area", log.getArea());
					json.put("max_speed", log.getSpeed());
					json.put("latitude", log.getLat());
					json.put("longitude", log.getLon());
					json.put("date_time", log.getDateTime());
				    //json.put("driver_id", log.getDriver_id());
					json.put("status", log.getStatus());
					json.put("vehicleNo",localSP.getString("driver_id", "").toString());
					json.put("password", localSP.getString("password", "").toString());
					
					HttpParams httpParams = new BasicHttpParams();
					HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
					HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
					HttpClient httpclient = new DefaultHttpClient(httpParams);

					String url = "http://smartautomobile.donsej.com/index.php/api/error_log_data.php";

					HttpPost request = new HttpPost(url);

					request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
					request.setHeader("json", json.toString());

					ResponseHandler<String> responseHandler = new BasicResponseHandler();
					String responseBody = httpclient.execute(request,
							responseHandler);

					// Parse
					JSONObject json1 = new JSONObject(responseBody);
					JSONArray jArray = json1.getJSONArray("posts");

					if (jArray.length() != 0) {

						for (int i = 0; i < jArray.length(); i++) {

							JSONObject e = jArray.getJSONObject(i);
							String s = e.getString("post");
							JSONObject jObject = new JSONObject(s);

							if (jObject.getString("message").equals("1")) {
								
								ds.updateRCSProfileSyncStatus(1);
							}

							else {
								 Log.v("success","Failed");
							}

						}

					}
					
				}


			} catch (Exception e) {
				
			}

			return null;
		}

	}
	
	
	
}
